package org.example.bankMessage;

import com.alibaba.fastjson.JSON;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.*;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.common.message.MessageQueue;
import org.apache.rocketmq.remoting.exception.RemotingException;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MessageProducer {


    public static void main(String[] args) throws MQClientException, RemotingException, InterruptedException, UnsupportedEncodingException {
        // 实例化消息生产者Producer
        DefaultMQProducer producer = new DefaultMQProducer("please_rename_unique_group_name");
        // 设置NameServer的地址
        producer.setNamesrvAddr("192.168.254.129:9876");

        //构建短信消息
        Map<String, Object> body = new HashMap<>();
        Integer accountId=null;
        body.put("remark", "短信内容");
        body.put("accountId", accountId);
        body.put("account", "账户");
        Message message=new Message("topic_test", JSON.toJSONString(body).getBytes());
        try {
            SendResult sendResult = producer.send(message, new MessageQueueSelector() {
                @Override
                public MessageQueue select(List<MessageQueue> list, Message message, Object arg) {
                    //这里的object arg就是send方法中的第三个参数
                    if (list == null || list.isEmpty()) {
                        return null;
                    }
                    int index = Math.abs(arg.hashCode()) % list.size();
                    return list.get(index < 0 ? 0 : index);
                }
            }, accountId);

            if ((sendResult.getSendStatus() == SendStatus.SEND_OK)) {
                throw new RuntimeException("消息发送异常" + sendResult.getSendStatus());
            }
        }catch (Throwable e){
            throw new RuntimeException("消息发送异常", e);
        }
    }
}
